package com.sgb.kjwl.view.ui.fragment.transport.company;

import android.graphics.Color;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.fondesa.recyclerviewdivider.DividerDecoration;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.sgb.kjwl.AppLazyFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragCargoManageBinding;
import com.sgb.kjwl.model.entity.transport.MotorcadListEntity;
import com.sgb.kjwl.model.entity.transport.SelfFleetEntity;
import com.sgb.kjwl.model.response.ListResponseV1;
import com.sgb.kjwl.view.constant.RouterKey;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LogisticsEvent;
import com.swgk.core.event.MenuEvent;
import com.sgb.kjwl.view.event.self.GoodsManageEvent;
import com.sgb.kjwl.view.ui.activity.transport.company.AddProprietaryFleetActivity;
import com.sgb.kjwl.view.ui.activity.transport.company.AffiliatedFleetDetailsActivity;
import com.sgb.kjwl.view.ui.adapter.self.logistics.ProprietaryItemAdapter;
import com.sgb.kjwl.viewmodel.transport.LinkItemModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.util.ArrayUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: 熊丽
 * @date: 2021/10/9 10:59
 * @Description: 车队列表内容页
 */
public class ProprietaryFleetFragment extends AppLazyFragment {
    LinkItemModel viewModel;
    FragCargoManageBinding binding;
    //货源列表
    private List<MotorcadListEntity> mList;
    private ProprietaryItemAdapter mAdapter;
    //
    private boolean mIsGeneralGoods;
    private int mPattern;
    private int mState;
    private int mPage = 1;

    public static ProprietaryFleetFragment newInstance( boolean isLinked) {
        ProprietaryFleetFragment fragment = new ProprietaryFleetFragment();
        Bundle args = new Bundle();
        args.putBoolean(RouterKey.BOOLEAN, isLinked);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        viewModel = new ViewModelProvider(this).get(  LinkItemModel.class);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.frag_cargo_manage, container, false);
        binding.setLifecycleOwner(this);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        return binding.getRoot();
    }

    @Override
    protected void onLazyLoad() {

        initIntentParams();
        initRecycler();
        initEvent();
        initData();
    }

    private void initIntentParams() {
        Bundle bundle = getArguments();
        if (bundle != null) {
            mIsGeneralGoods = getArguments().getBoolean(RouterKey.BOOLEAN, true);
            mPattern = mIsGeneralGoods ? 0 : 1;
        }
    }

    private void initRecycler() {
        mList = new ArrayList<>();
        mAdapter = new ProprietaryItemAdapter(mList);
        binding.rvCargoManage.setLayoutManager(new LinearLayoutManager(getActivity()));
        if (getActivity() != null) {
            DividerDecoration.builder(getActivity())
                    .showFirstDivider()
                    .color(Color.TRANSPARENT)
                    .size(10, TypedValue.COMPLEX_UNIT_DIP)
                    .build()
                    .addTo(binding.rvCargoManage);
        }
        mAdapter.bindToRecyclerView(binding.rvCargoManage);
    }

    private void initEvent() {

        binding.srlCargoManage.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                viewModel.getGoodsManagerList(getContext(), mPage, null,1);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refreshData();
            }
        });
        mAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            MotorcadListEntity info = mList.get(position);
            itemClick(view, info);
        });
        //接口回调
       viewModel.ldMotorcad.observe(this, this::refreshUIByData);
    }

    private void initData() {
        refreshData();
    }

    public void refreshData() {
        if (mAdapter != null) {
            mPage = 1;
            viewModel.getGoodsManagerList(getContext(), mPage, null,1);
        }
    }

    /**
     * 删除提示
     */
    private void showDelDialog(MotorcadListEntity data) {
        new RoundDialog.Builder(getActivity())
                .title("温馨提示")
                .content("您确定要删除"+data.getMotorcadeName()+"车队吗？")
                .confirmCallback(v -> viewModel.deleteNo(getContext(), data.getNo()))
                .show();
    }
    /**
     * 同步数据
     */
    private void refreshUIByData(ListResponseV1<List<MotorcadListEntity>> listResponse) {
        binding.srlCargoManage.finishRefresh();
        binding.srlCargoManage.finishLoadMore();
        if (listResponse == null) {
            return;
        }
        //设置数据
        if (listResponse.getPageNumber() == 1) {
            mList.clear();
        }
        if (listResponse.getList() != null) {
            for (int i = 0;i<listResponse.getList().size();i++){
                listResponse.getList().get(i).setType(1);
            }
            mList.addAll(listResponse.getList());
        }
        if (ArrayUtil.isNullOrEmpty(mList)) {
            mAdapter.setEmptyView(R.layout.layout_null_list_logistics);
        }
        mAdapter.notifyDataSetChanged();
        //更新页码
        if (listResponse.getPageNumber() < listResponse.getPageSize()) {
                mPage = listResponse.getPageNumber() + 1;
                binding.srlCargoManage.setNoMoreData(false);
        } else {
            binding.srlCargoManage.finishLoadMoreWithNoMoreData();
        }
    }
    /**
     * 列表按钮点击事件
     */
    private void itemClick(View view, MotorcadListEntity info) {
        if (view.getId() == R.id.tv_item_fleet_edit) {
            SelfFleetEntity selfFleetEntity = new SelfFleetEntity();
            selfFleetEntity.setMotorcadeNo(info.getMotorcadeNo());
            selfFleetEntity.setTelphone(info.getTelephone());
            selfFleetEntity.setName(info.getName());
            selfFleetEntity.setMotorcadeName(info.getMotorcadeName());
            selfFleetEntity.setId(info.getId());
            AddProprietaryFleetActivity.start(getContext(),selfFleetEntity);
        } else if (view.getId() == R.id.tv_item_fleet_del ) {
            showDelDialog(info);
        }else if (view.getId() == R.id.cl_fleet_item){
            AffiliatedFleetDetailsActivity.start(getContext(),true,info.getMotorcadeNo());
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateCount(GoodsManageEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_REFRESH_AFFILIATED_SUCCESS) {
            refreshAllData();
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refresh(LogisticsEvent event) {
        //解绑/绑定司机，添加/修改车辆信息刷新列表
        if (event.getMessageTag() == EventConstant.EVENT_UNBIND_DRIVER||event.getMessageTag()==EventConstant.EVENT_BIND_DRIVER)
        {
            refreshAllData();
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(MenuEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_REFRESH_PRO_DRIVER) {
            refreshAllData();
        }
    }
    private void refreshAllData() {
        mPage = 1;
        viewModel.getGoodsManagerList(getContext(), mPage, null,1);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
